//
//  CollectionViewController.m
//  project_delicious
//
//  Created by dlios on 15-3-24.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "CollectionViewController.h"
#import "TheFoodCell.h"
#import "TheFoodDetailsViewController.h"
#import "SearchViewController.h"
#import "UIColor+AddColor.h"

@interface CollectionViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSString *hid;
@property (nonatomic, retain) NSString *gid;
@property (nonatomic, retain) NSString *currPage;
@property (nonatomic, retain) NSString *maxPage;
@property (nonatomic, retain) UICollectionView *collectView;
@property (nonatomic, retain) NSMutableArray *arr1;
@property (nonatomic, retain) MBProgressHUD *hud;

@end

@implementation CollectionViewController
- (void)dealloc
{
    [_hud release];

    [_arr1 release];
    [_collectView release];
    [_maxPage release];
    [_currPage release];
    [_reStrP release];
    [_reStrS release];
    [_preStrCook release];
    [_suffStrCook release];
    [_preStrMat release];
    [_suffStrMat release];
    [_hid release];
    [_preStr release];
    [_suffStr release];
    [_str release];
    [_arr release];
    [super dealloc];
}
- (NSURL *)strChangeUrl:(NSString *)str
{
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:str];
    return url;
}
- (void)netWorkRequest:(NSString *)str
{
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        self.arr1 = [NSMutableArray array];
        self.arr = [responseObject objectForKey:@"data"];
        if (self.arr.count == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起" message:@"暂无数据,您的搜索有误,请重新输入" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alertView show];
            [self.view addSubview:alertView];
            [alertView release];
        }
        //        CCHexagonFlowLayout *flow = [[CCHexagonFlowLayout alloc] init];
        //        flow.itemSize = CGSizeMake(self.view.frame.size.width / 2 - 20, self.view.frame.size.height / 3);
        //        flow.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        
        // Build layout
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];

        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.minimumInteritemSpacing = 5.0;
        flow.minimumLineSpacing = 5.0;
        flow.itemSize = CGSizeMake(self.view.frame.size.width / 2 - 20, self.view.frame.size.height / 3);
        flow.sectionInset = UIEdgeInsetsMake(20.0, 15.0, 20.0, 15.0);

        self.collectView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flow];
        self.collectView.backgroundColor = [UIColor clearColor];

        self.collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) collectionViewLayout:flow];
        NSLog(@"_+_+_+%f", HEIGHT);
        self.collectView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"foodcoB.png"]];

        self.collectView.delegate = self;
        self.collectView.dataSource = self;
        self.collectView.userInteractionEnabled = YES;
        [self.view addSubview:self.collectView];
        [_collectView release];
        [_collectView registerClass:[TheFoodCell class] forCellWithReuseIdentifier:@"guo"];
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.currPage = [[responseObject objectForKey:@"bean"] objectForKey:@"curPage"];
        //        NSLog(@"currPage:%@", self.currPage);
        self.maxPage = [[responseObject objectForKey:@"bean"] objectForKey:@"maxPageNumber"];
        
        for (NSMutableDictionary *dic in self.arr) {
            [self.arr1 addObject:dic];
        }
        
        [_collectView addFooterWithTarget:self action:@selector(footReAction:)];
        [_collectView addHeaderWithTarget:self action:@selector(headReAction:)];
        
        [_hud removeFromSuperview];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"发生错误: %@", error );
    }];
}
//转菊花
- (void)mbHud
{
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    self.hud.labelText = @"Loading...";
    //self.hud.detailsLabelText = @"正在为您加载";
    [self.view addSubview:self.hud];
    [_hud release];
    [_hud show:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self mbHud];
    
    
   
    self.tabBarController.tabBar.hidden = YES;
    
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"IMG_1345.JPG"]];
    [self netWorkRequest:self.str];
}
- (void)headReAction:(UICollectionView *)collection
{
//    self.currPage = @"1";
//    self.str = [[self.reStrP stringByAppendingString:self.currPage] stringByAppendingString:self.reStrS];
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    self.str = [self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    [manager GET:self.str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        self.arr1 = [NSMutableArray array];
//        self.arr1 = [responseObject objectForKey:@"data"];
//        //NSLog(@"====+++==%ld", self.arr1.count);
//        [self.collectView headerEndRefreshing];
//        [self.collectView reloadData];
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"发生错误: %@", error );
//    }];
    [self.collectView headerEndRefreshing];
}
- (void)footReAction:(UICollectionView *)collection
{
  
    NSInteger n = [self.currPage integerValue];
    NSInteger maxPage = [self.maxPage integerValue];
    //NSLog(@"currPage:%@", self.currPage);
    //NSLog(@"shuaxin" );
    if (n < maxPage) {
        n = n + 1;
        self.currPage = [NSString stringWithFormat:@"%ld", n];
        self.str = [[self.reStrP stringByAppendingString:self.currPage] stringByAppendingString:self.reStrS];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        self.str = [self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [manager GET:self.str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSMutableArray *arr = [responseObject objectForKey:@"data"];
            for (NSMutableDictionary *dic in arr) {
                [self.arr1 addObject:dic];
            }
            //NSLog(@"====+++==%ld", self.arr1.count);
            [self.collectView footerEndRefreshing];
            [self.collectView reloadData];
 
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"发生错误: %@", error );
        }];


    } else {
        [self.collectView footerEndRefreshing];
//        NSString *const MJRefreshFooterRefreshing = @"已经是最后一页";
        
    }
//    self.collectView.contentSize = CGSizeMake(0, self.collectView.frame.origin.y + self.collectView.frame.size.height * 3);
    
    
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor colorFromHexCode:@"FFFFCC"];

    //self.navigationController.navigationBar.barTintColor = [UIColor colorFromHexCode:@"CCFFCC"];
    self.tabBarController.tabBar.hidden = YES;
//    self.navigationController.navigationBar.translucent = NO;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    self.arr1 = [NSMutableArray arrayWithArray:self.arr];
    return self.arr1.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TheFoodCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"guo" forIndexPath:indexPath];
    NSString *str = [[self.arr1 objectAtIndex:indexPath.item] objectForKey:@"imagePathLandscape"];
    cell.picImageView.layer.cornerRadius = 20;
    cell.picImageView.layer.masksToBounds = YES;
    [cell.picImageView setImageWithURL:[self strChangeUrl:str]];
    cell.nameLabel.text = [[self.arr1 objectAtIndex:indexPath.item] objectForKey:@"name"];
    //cell.collLabel.text = [[self.arr1 objectAtIndex:indexPath.item] objectForKey:@"clickCount"];
    
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TheFoodDetailsViewController *foodView = [[TheFoodDetailsViewController alloc] init];
    self.hid = [[self.arr1 objectAtIndex:indexPath.row] objectForKey:@"vegetable_id"];
    
    NSString *str = [[self.preStr stringByAppendingString:self.hid] stringByAppendingString:self.suffStr];
    NSString *str1 = [[self.preStrMat stringByAppendingString:self.hid] stringByAppendingString:self.suffStrMat];
    foodView.str = str;
    foodView.str1 = str1;
    foodView.fid = [[self.preStrCook stringByAppendingString:self.hid] stringByAppendingString:self.suffStrCook];

    
    [self.navigationController pushViewController:foodView animated:YES];
    [foodView release];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
